package durst.action.account;

import java.sql.SQLException;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidationErrors;
import net.sourceforge.stripes.validation.ValidationMethod;

import com.sdicons.json.mapper.MapperException;

import durst.action.CalendarBasicAction;
import durst.data.Account;
import durst.data.dao.DaoFactory;

public class ManageAccountActionBean extends CalendarBasicAction {
	@Validate(required = true, on="alter", minlength = 6, maxlength = 20)
	private String current;
	
	@Validate(required = true, on="alter", minlength = 6, maxlength = 20)
	private String newpass;
	
	@Validate(required = true, on="alter", minlength = 6, maxlength = 20, expression="this == newpass")
	private String confirm;
	
	@ValidationMethod(on = "alter")
	public void checkPasswords(ValidationErrors errors) {
		if (!context.getAccount().validatePassword(current)) 
			errors.add("current", new SimpleError("Entered password does not match current password"));
	}
	
	@DefaultHandler
	public Resolution view() throws SQLException, MapperException {
		context.getRequest().setAttribute("account", context.getAccount());
		context.getRequest().setAttribute("cal.id", 1);
		return new ForwardResolution("/account/account.jsp");
	}

	public Resolution alter() throws SQLException {
		context.getAccount().changePassword(newpass);
		DaoFactory.getInstance().createDao(Account.class).update(context.getAccount());
		
		return new RedirectResolution(ManageAccountActionBean.class);
	}

	public String getCurrent() {
		return current;
	}

	public void setCurrent(String current) {
		this.current = current;
	}

	public String getNewpass() {
		return newpass;
	}

	public void setNewpass(String newpass) {
		this.newpass = newpass;
	}

	public String getConfirm() {
		return confirm;
	}

	public void setConfirm(String confirm) {
		this.confirm = confirm;
	}
}
